
public class Board {
	
	final static char EMPTY = ' ';
	final static char CROSS = 'x';
	final static char ZERO = '0';
	
	char  cells[][];
	
	public void Initialize()
	{
		cells = new char[3][3];
		
		for(int i=0;i<3;i=i+1)
		{
			for(int j=0;j<3;j=j+1)
			{
				cells[i][j] = EMPTY;
			}
		}
	}
	
	public void print()
	{
		System.out.println("-------------");
		for(int i=0;i<3;i=i+1)
		{
			System.out.print("| ");
			for(int j=0;j<3;j=j+1)
			{
				System.out.print(cells[i][j] + " | ");
			}
			System.out.println();
			System.out.println("-------------");
		}
	}
	
	int rowForCellNumber(int cellNumber)
	{
		return (cellNumber - 1) / 3;
	}
	
	int columnForCellNumber(int cellNumber)
	{
		return (cellNumber - 1) % 3;
	}
	
	boolean isStepValid(char piece, int cellNumber)
	{
		int i = rowForCellNumber(cellNumber);
		int j = columnForCellNumber(cellNumber);

		if (i < 0 || i >= 3 || j < 0 || j >= 3 || 
				cells[i][j] == CROSS || 
				cells[i][j] == ZERO) 
		{
			return false;
		}

		return true;
	}
	
	boolean setPieceForCell(char piece, int cellNumber) 
	{
		if (isStepValid(piece, cellNumber))
		{
			cells[rowForCellNumber(cellNumber)][columnForCellNumber(cellNumber)] = piece;
			return true;
		}

		return false;
	}
	
	void clearCell(int cellNumber) 
	{
		cells[rowForCellNumber(cellNumber)][columnForCellNumber(cellNumber)] = Board.EMPTY;
	}

	public boolean isBoardFull() 
	{
		for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				if (cells[i][j] != CROSS && cells[i][j] != ZERO)
				{
					return false;
				}
			}
		}

		return true;
	}
	
	
	public boolean isBoardEmpty()
	{
		for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				if (cells[i][j] == CROSS || cells[i][j] == ZERO)
				{
					return false;
				}
			}
		}

		return true;
	}

	static int cellNumberFor(int i, int j)
	{
		return i * 3 + j + 1;
	}
	
	public boolean checkForWin()
	{
		return (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin());
	}

	private boolean checkRowsForWin() 
	{
		for (int i = 0; i < 3; i++)
		{
			if (checkRowCol(cells[i][0], cells[i][1], cells[i][2]) == true)
			{
				return true;
			}
		}
		return false;
	}

	private boolean checkColumnsForWin()
	{
		for (int i = 0; i < 3; i++)
		{
			if (checkRowCol(cells[0][i], cells[1][i], cells[2][i]) == true)
			{
				return true;
			}
		}
		return false;
	}

	private boolean checkDiagonalsForWin()
	{
		return ((checkRowCol(cells[0][0], cells[1][1], cells[2][2]) == true) || 
				(checkRowCol(cells[0][2], cells[1][1], cells[2][0]) == true));
	}

	private boolean checkRowCol(char c1, char c2, char c3) 
	{
		return ((c1 == ZERO || c1==CROSS) && (c1 == c2) && (c2 == c3));
	}

}
